package com.dalonedrow.engine.ui.base.menu;

import com.dalonedrow.engine.sprite.base.SimpleDimension;


/**
 * Implements a horizontal menu group.
 * @author Donald
 */
public final class HorizontalMenu extends MenuGroup {
	/** the {@link GuiComponent}'s preferred size. */
	private SimpleDimension	preferredSize	= new SimpleDimension(0, 0);
	/**
	 * {@inheritDoc}
	 */
	@Override
	public SimpleDimension getPreferredSize() {
		if (preferredSize.width == 0
				|| preferredSize.height == 0) {
			int w = 0, h = 0;
			if (getBorder() != null) {
				w = getBorder().getInsets().left;
				w += getBorder().getInsets().right;
				h = getBorder().getInsets().top;
				h += getBorder().getInsets().bottom;
			}
			w += getInsets().left + getInsets().right;
			h += getInsets().top + getInsets().bottom;
			int maxChildH = 0;
			for (int i = 0; i < super.getNumItems(); i++) {
				maxChildH = Math.max(maxChildH,
						super.getItem(i).getPreferredSize().height);
				w += super.getItem(i).getPreferredSize().width;
			}
			for (int i = 0; i < super.getNumItems(); i++) {
				super.getItem(i).setPreferredSize(
						super.getItem(i).getPreferredSize().width,
						maxChildH
						);
			}
			h += maxChildH;
			preferredSize = new SimpleDimension(w, h);
			if (getBorder() != null) {
				getBorder().setPreferredSize(w, h);
			}
		}
		return preferredSize;
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void prepareForRendering() throws Exception {
		if (super.isVisible()
				&& super.getPosition() != null) {
			if (super.getBorder() != null) {
				super.getBorder().prepareForRendering();
			}
			for (int i = 0; i < super.getNumItems(); i++) {
				super.getItem(i).prepareForRendering();
			}
		}
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setPosition(final double x, final double y, final double z) {
		super.setPosition(x, y, z);
		// position all children
		double childX = x, childY = y, childZ = z + 1;
		if (super.getBorder() != null) {
			super.getBorder().setPosition(x, y, z);
			childX += super.getBorder().getInsets().left;
			childY += super.getBorder().getInsets().bottom;
		}
		childX += getInsets().left;
		childY -= getInsets().bottom;
		for (int i = 0; i < super.getNumItems(); i++) {
			super.getItem(i).setPosition(childX, childY, childZ);
			childX += super.getItem(i).getPreferredSize().width;
		}
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setPreferredSize(final int width, final int height) {
		preferredSize.width = width;
		preferredSize.height = height;
	}
}
